﻿using System;
using System.Linq;
using System.Web.Configuration;
using Mollie.iDEAL;
using SuperSimpleWebshop.Common;
using SuperSimpleWebshop.Domain;
using SuperSimpleWebshop.Domain.Helpers;
using SuperSimpleWebshop.Domain.Interfaces;
using SuperSimpleWebshop.Domain.Repositories;
using umbraco;
using umbraco.BusinessLogic;
using umbraco.presentation.nodeFactory;
using System.Threading;

namespace SuperSimpleWebshop.Payment.Mollie
{
    public class MolliePaymentRequestHandler : IPaymentRequestHandler
    {
        #region IPaymentRequestHandler Members
        public string GetName()
        {
            return "Mollie";
        }

        public PaymentRequest CreatePaymentRequest(Order order)
        {
            try
            {
                var paymentProvider = new OrderRepository().GetAllPaymentProviders().Where(x => x.Name == order.OrderInfo.PaymentInfo.PaymentProviderName).FirstOrDefault();

                #region build urls
                var baseUrl = string.Format("http://{0}", library.GetCurrentDomains(Node.GetCurrent().Id).FirstOrDefault().Name);
                baseUrl = baseUrl.Substring(0, baseUrl.LastIndexOf("/"));

                var oldUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
                var oldCulture = System.Threading.Thread.CurrentThread.CurrentCulture;

                var shopAliasNode = ShopAliasHelper.GetAllShopAlias().Where(x => x.Name.ToLower() == order.OrderInfo.ShopAlias.Alias.ToLower()).FirstOrDefault();

                Thread.CurrentThread.CurrentCulture = shopAliasNode.CultureInfo;
                Thread.CurrentThread.CurrentUICulture = shopAliasNode.CultureInfo;

                var nodeId = DomainHelper.GetNodeIdForDocument("sswsOrderProcessNode", library.GetDictionaryItem("PaymentConfirmation"), ShopAliasHelper.GetCurrentShopAlias());
                var cancelNodeId = DomainHelper.GetNodeIdForDocument("sswsOrderProcessNode", library.GetDictionaryItem("PaymentConfirmationFailed"), ShopAliasHelper.GetCurrentShopAlias());

                System.Threading.Thread.CurrentThread.CurrentUICulture = oldUICulture;
                System.Threading.Thread.CurrentThread.CurrentCulture = oldCulture;

                var returnUrl = string.Format("{0}{1}", baseUrl, library.NiceUrl(nodeId));
                var cancelUrl = string.Format("{0}{1}", baseUrl, library.NiceUrl(cancelNodeId));
                string reportUrl = string.Format("{0}{1}", baseUrl, library.NiceUrl(paymentProvider.Id));
                #endregion


                var helper = new PaymentConfigHelper(GetName());

                var paymentMethods = helper.PaymentProviderMethods;

                var idealFetch = new IdealFetch
                    (
                        helper.Settings["partnerId"], //partnerId
                        helper.TestModeEnabled,
                        string.Empty,
                        reportUrl,
                        returnUrl,
                        order.OrderInfo.PaymentInfo.PaymentMethodId,
                        OrderHelper.GetTotalAmountUsingVATCheck()
                    );

                order.OrderInfo.PaymentInfo.PaymentTransactionId = idealFetch.TransactionId;

                if (!idealFetch.Error)
                {
                    order.OrderInfo.PaymentInfo.PaymentParameterRenderMethod = PaymentParameterRenderMethod.QueryString;
                    order.OrderInfo.PaymentInfo.PaymentURL = idealFetch.Url;
                    order.OrderInfo.PaymentInfo.PaymentParameters = order.OrderInfo.PaymentInfo.PaymentURL.Split('?')[1];
                }
                else
                {
                    Log.Add(LogTypes.Error, 0, "MolliePaymentRequestHandler.CreatePaymentRequest: idealFetch.Error: " + idealFetch.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Error, 0, "MolliePaymentRequestHandler.CreatePaymentRequest: " + ex.ToString());
            }

            return null;
        }
        #endregion
    }
}
